<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * 经纪公司管理
 *
 * @icon fa fa-circle-o
 */
class Ibec extends Backend
{

    /**
     * Ibec模型对象
     * @var \app\common\model\Ibec
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Ibec;

    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        if(count($list)==1){
            $count=\app\common\model\Staff::where(["ibec_id"=>$list[0]["id"]])->count();
            if($count>=1) $this->error("该公司存在员工，无法删除");
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $num=\app\common\model\Staff::where(["ibec_id"=>$list[0]["id"]])->count();
                if($num==0){
                    $count += $item->delete();
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
